package net.muliba.wifitransfer

import android.content.Context
import android.net.wifi.WifiManager
import android.os.Bundle
import android.os.Environment
import android.os.Looper
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.WindowManager
import com.alibaba.fastjson.JSON
import com.koushikdutta.async.AsyncServer
import com.koushikdutta.async.http.server.AsyncHttpServer
import kotlinx.android.synthetic.main.activity_main.*
import java.io.*
import java.net.URLDecoder
import java.nio.charset.Charset






class MainActivity : AppCompatActivity() {

    private val port = 54321 //端口
    private val server: AsyncHttpServer by lazy { AsyncHttpServer() }
    private val mAsyncServer: AsyncServer by lazy { AsyncServer() }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)//屏幕长亮
        checkWifiEnable()
    }

    private fun checkWifiEnable() {
        //获取wifi服务
        val wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
        if (!wifiManager.isWifiEnabled) {
            ipAddress.text = "没有开启wifi无法使用本功能！ 请开启wifi后再点击这段文字刷新。"
            ipAddress.setOnClickListener {
                checkWifiEnable()
            }
        } else {
            ipAddress.setOnClickListener(null)
            val wifiInfo = wifiManager.connectionInfo
            val ipInt = wifiInfo.ipAddress
            val ip = intToIpString(ipInt)
            ipAddress.text = "请在电脑浏览器地址栏输入：\nhttp://$ip:$port"
            server.get("/") { _, response ->
                try {
                    response?.send(getIndexContent())
                } catch (e: IOException) {
                    e.printStackTrace();
                    response?.code(500)?.end()
                }
            }
            server.get("/img/.*", { request, response ->
                try {
                    var fullPath  = request.path.replace("/img/", "")
//                    var fullPath = request.path
                    fullPath = fullPath.replace("%20", " ")
                    var resourceName = fullPath
                    if (resourceName.startsWith("/")) {
                        resourceName = resourceName.substring(1)
                    }
                    if (resourceName.indexOf("?") > 0) {
                        resourceName = resourceName.substring(0, resourceName.indexOf("?"))
                    }
                    response.setContentType("image/png")
                    Log.i("TAG", "resource name: $resourceName")
                    val bInputStream = BufferedInputStream(assets.open(resourceName))
                    response.sendStream(bInputStream, bInputStream.available().toLong())
                } catch (e: IOException) {
                    e.printStackTrace()
                    response.code(404).end()
                }
            })
            server.get("/folder/.*", { request, response ->
                val path  = request.path.replace("/folder/", "")
                Log.i("TAG", "folder path: $path")
                val abPath = Environment.getExternalStorageDirectory().path+File.separator+path
                Log.i("TAG", "absolute path: $abPath")
                val dir = File(abPath)
                val list = ArrayList<FileData>()
                dir.listFiles().map {
                    val data = FileData()
                    if (it.isDirectory){
                        data.type = FileType.folder.type
                    }else {
                        when(it.extension.toLowerCase()){
                            "jpg", "jepg", "png", "gif" -> data.type = FileType.img.type
                            "mp4" -> data.type = FileType.video.type
                            else -> data.type = FileType.file.type
                        }
                    }
                    data.name = it.name
                    list.add(data)
                }
                val responseData = FileResponse("/"+path, list)
                val jsonString = JSON.toJSONString(responseData)
                Log.i("TAG", "response data: $jsonString")
                response.send(jsonString)
            })
            server.get("/file/.*", {request, response ->
                var path  = request.path.replace("/file/", "")
                Log.i("TAG", "file path: $path")
                try {
                    path = URLDecoder.decode(path, "utf-8")
                } catch (e: UnsupportedEncodingException) {
                    e.printStackTrace()
                }
                Log.i("TAG", "file path: $path")
                val abPath = Environment.getExternalStorageDirectory().path+File.separator+path
                Log.i("TAG", "absolute path: $abPath")
                val file = File(abPath)
                if (file.exists() && file.isFile) {
                    try {
                        val fis = FileInputStream(file)
                        response.sendStream(fis, fis.available().toLong())
                    } catch (e: Exception) {
                        e.printStackTrace()
                        response.code(404).send("Not found!")
                    }
                }else{
                    response.code(404).send("Not found!")
                }
            })
            server.listen(mAsyncServer, port)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        server.stop()
        mAsyncServer.stop()
    }

    private fun isMainThread(): Boolean = Looper.getMainLooper() == Looper.myLooper()
    private fun getIndexContent(): String {
        var bInputStream: BufferedInputStream? = null
        try {
            bInputStream = BufferedInputStream(assets.open("index.html"))
            var baos = ByteArrayOutputStream()
            var len = 0
            val tmp = ByteArray(10240)
            len = bInputStream?.read(tmp)
            while (len > 0) {
                baos.write(tmp, 0, len)
                len = bInputStream?.read(tmp)
            }
            return String(baos.toByteArray(), Charset.forName("utf-8"))
        } catch (e: IOException) {
            Log.e("TAG", "read file fail", e)
        } finally {
            if (bInputStream != null) {
                try {
                    bInputStream.close()
                } catch (e: Exception) {
                    Log.e("TAG", "close fail", e)
                }
            }
        }
        return "文件读取失败!"
    }

    private fun intToIpString(ipInt: Int): String {
        return (ipInt and 0xFF).toString() + "." +
                (ipInt shr 8 and 0xFF).toString() + "." +
                (ipInt shr 16 and 0xFF).toString() + "." +
                (ipInt shr 24 and 0xFF)
    }
}
